import { getToken, setToken, removeToken } from '@/utils/auth'
import { permissionMenu } from '@/router'
import api from '@/utils/api'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    menus: undefined,
    router: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MENU: (state, menus) => {
    state.menus = menus
  },
  SET_ROUTER: (state, router) => {
    state.router = router
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      api
        .post('/api/admin/login', userInfo)
        .then((res) => {
          if (res.code === 200) {
            commit('SET_TOKEN', res.data)
            setToken(res.data)
          }
          resolve()
        })
        .catch((error) => {
          console.error(error)
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      api
        .get('/api/admin/get_info', { token: state.token })
        .then((res) => {
          if (res.code === 200) {
            const router = permissionMenu(res.data.menus)
            commit('SET_MENU', res.data.menus)
            commit('SET_ROUTER', router)
            resolve(router)
          } else reject(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      api.get('/api/admin/logout')
        .then(() => {
          removeToken() // must remove  token  first
          commit('SET_TOKEN', undefined)
          commit('SET_MENU', [])
          commit('SET_ROUTER', [])
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
